<template>
  <div>
    <!--成本控制策划表 -->
    <a-form-model ref="ruleForm" class="table-form" :model="form" :label-col="{ span: 6 }" :wrapper-col="{ span: 18 }" :rules="editable ? rules : {}">
      <a-spin :spinning="loading">
        <!-- 表单 -->
        <a-card>
          <title-name title="成本控制策划表"></title-name>
          <a-table bordered :data-source="form.detailList" :columns="columns" rowKey="stringId" :pagination="false">
            <template v-for="(item, index) in editableKey" :slot="item" slot-scope="text, record, index">
              <div v-if="editable" :key="item" :class="cellClass(record, item)">
                <BaseInput v-model="record[item]" @change="handleChange(item, record, $event)" :maxLength="300"/>
                <!-- <a-input :class="validate && !record[item] ? 'validate_err' : ''" v-model="record[item]" @change="handleChange(item, record, $event)"  :maxLength="300" placeholder='请输入'/> -->
              </div>
              <template v-else>
                <span>{{record[item]}}</span>
              </template>
            </template>
            
            <template slot="action" slot-scope="text, record, index">
              <a-popconfirm v-if="editable" title="确定要删除?" @confirm="() => handleDel(record, index)">
                <a>删除</a>
              </a-popconfirm>
            </template>
          </a-table>
          
          <a-button type="primary" class="mt12" :disabled="!editable" icon="plus" @click="handleManage"> 增行 </a-button>
        </a-card>
      </a-spin>
    </a-form-model>
  </div>
</template>
<script>
import { getList, update } from '@/api/projectManagementPlanning/costControl'
import { getGuid } from '../../projectPlanningTaskList/config.js'
export default {
  name: 'CostControl' + Date.now(),
  components: {
  },
  props: {
    baseFormInfo: {
      type: Object,
      default: () => {}
    },
  },
  data() {
    return {
      loading: false, // 加载控件
      validate: false,
      form: {
        detailList: []
      },
      rules: {
      }, // 校验规则
      editableKey: [
        'planningProject',
        'controlObjective',
        'mainMeasure',
        'chargePersonName',
        'remark',
      ]
    }
  },
  computed: {
    cellClass() {
      return (record, item) => {
        if (item == 'remark') return ''
        if (this.validate && (record[item] == undefined || record[item] == null || record[item] === '')) {
          return 'requiredFormItem validate_err'
        } else {
          return 'requiredFormItem'
        }
      }
    },
    columns() {
      return [
        {
          title: '序号',
          dataIndex: 'index',
          width: 80,
          customRender(text, record, index) {
            return index + 1;
          }
        },
        {
          title: '策划项目',
          dataIndex: 'planningProject',
          width: 200,
          scopedSlots: { customRender: 'planningProject' },
        },
        {
          title: '控制目标',
          dataIndex: 'controlObjective',
          width: 200,
          scopedSlots: { customRender: 'controlObjective' },
        },
        {
          title: '主要措施',
          dataIndex: 'mainMeasure',
          scopedSlots: { customRender: 'mainMeasure' },
        },
        {
          title: '责任人',
          dataIndex: 'chargePersonName',
          width: 200,
          scopedSlots: { customRender: 'chargePersonName' },
        },
        {
          title: '备注',
          dataIndex: 'remark',
          width: 200,
          scopedSlots: { customRender: 'remark' },
        },
        {
          title: '操作',
          dataIndex: 'action',
          width: 100,
          scopedSlots: { customRender: 'action' }
        }
      ]
    },
    pageType() {
      return this.$route.query.pageType
    },
    editable() {
      return this.$route.query.editModel == 1
    },
    planId() {
      return this.$route.query.id
    }
  },
  mounted() {
    this.getListData()
  },
  methods: {
    getListData() {
      let param = {
        isNew: this.$route.query.version ? 1 : 0,
        planId: this.planId,
      }
      if (this.$route.query.version) {
        param.version = this.$route.query.version
      }
      getList(param).then((res) => {
        if (res.code == 200 || res.code == 0) {
          if (res.data.length) {
            this.form.detailList = res.data
          }
        }
      })
    },
    handleManage() {
      this.form.detailList.push({
        stringId: getGuid(),
        planningProject: '',
        controlObjective: '',
        mainMeasure: '',
        chargePersonName: '',
        remark: '',
      })
    },
    handleDel(record, index) {
      let idx = this.form.detailList.findIndex((e) => {
        return (e.stringId == record.stringId) || (e.id == record.stringId)
      })
      this.form.detailList.splice(idx, 1)
    },
    handleChange(key, record, e) {
      this.form.detailList = this.form.detailList.map((item, index) => {
        if (item.stringId == e.stringId) {
          item[key] = e.target.value
        }
        return item
      })
    },
    CostControlSubmit(e) {
      // this.validate = true
      let _this = this
      let flag = this.validateForm()
      if (!flag) {
        this.$warning({
          title: '温馨提示',
          content: '请将数据填写完整',
          okText: '确定'
        });
        return
      }
      this.$confirm({
        okText: '确认',
        okType: 'warning',
        cancelText: '取消',
        title: '提交?',
        content: `请确认是否要提交？`,
        onOk() {
          _this.submitForm(1)
        },
        onCancel() {
        },
      })
    },
    submitForm(type) {
      let param = {
        planCostControlList: this.form.detailList
      };
      param.isChange = this.pageType == 'change' ? 0 : 1; // 是变更还是编辑按钮（ 0：变更|1：编辑）
      param.isSubmit = type; // 按钮（ 0：保存草稿按钮|1：提交按钮）编辑使用
      param.planId = this.planId;
      param.version = this.form.detailList[0].version
      
      return update(param).then((res) => {
        if (res.code == 200 || res.code == 0) {
          let msg = type == 1 ? '提交' : '保存'
          this.$message.success(`${msg}成功！`);
          this.$close();
        }
      })
    },
    validateForm() {
      let flag = true
      if (this.form.detailList.length == 0) {
        this.$warning({
          title: '温馨提示',
          content: '请至少填写一行数据',
          okText: '确定'
        });
        return false
      }
      this.form.detailList.forEach((sub, idx) => {
        this.editableKey.map((e, i) => {
          if (e !== 'remark' && (sub[e] === '' || sub[e] == undefined || sub[e] == null)) {
            flag = false
          }
        })
      })
      return flag
    },
    CostControlSaveDrafts(e) {
      // this.validate = false
      this.submitForm(0)
    },
  }
}
</script>
<style lang="less" scoped>
  /deep/ .requiredFormItem.validate_err .ant-input:not([disabled]),
  /deep/ .requiredFormItem.validate_err .ant-time-picker-input,
  /deep/ .requiredFormItem.validate_err .ant-select:not(.ant-select-disabled) .ant-select-selection,
  /deep/ .requiredFormItem.validate_err .ant-calendar-picker-input,
  /deep/ .requiredFormItem.validate_err .ant-input-number-input,
  /deep/ .requiredFormItem.validate_err .ant-cascader-picker {
    border-color: #f5222d;
  }
</style>
